package database

// package minios3 implements a subset of the Amazon S3 API.
import (
	"bytes"
	"context"
	"encoding/base64"
	"time"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/zeromicro/go-zero/core/logc"
)

// 定义minio认证结构体
type MinioAuth struct {
	AccessKey string `json:"AccessKey"`
	SecretKey string `json:"SecretKey"`
	Endpoint  string `json:"Endpoint"`
	Bucket    string `json:"Bucket"`
	UseSSL    bool   `json:"UseSSL"`
}

type MinioClient struct {
	*minio.Client
}

func NewMinio(endpoint, accessKeyID, secretAccessKey string, ssl bool) (*MinioClient, error) {
	c, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: ssl,
	})
	if err != nil {
		return nil, err
	}
	return &MinioClient{c}, nil
}

func (c *MinioClient) BucketExists(ctx context.Context, name string) bool {
	_, err := c.Client.BucketExists(ctx, name)
	return err == nil
}

func (c *MinioClient) CreateBucket(ctx context.Context, name string, region string) error {
	return c.Client.MakeBucket(ctx, name, minio.MakeBucketOptions{Region: region})
}

// 上传图片到指定bucket
func (c *MinioClient) PutObject(ctx context.Context, bucketName, objectName string, data string) (string, error) {
	imageData, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		logc.Errorf(ctx, "base64 decode error: %v", err)
	}

	// 创建一个bytes.Reader
	reader := bytes.NewReader(imageData)

	// 上传base64编码的图片到bucket
	_, err = c.Client.PutObject(ctx, bucketName, objectName, reader, int64(len(imageData)), minio.PutObjectOptions{
		ContentType: "image/jpeg", // 设置文件类型
	})
	if err != nil {
		return "", err
	}
	// 返回minio上传图片的url地址
	url, err := c.Client.PresignedGetObject(ctx, bucketName, objectName, 60*time.Minute, nil)
	if err != nil {
		return "", err
	}

	return url.String(), err
}
